package com.gs.SynAntiWandering.activity.member;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.gs.SynAntiWandering.R;
import com.gs.SynAntiWandering.activity.base.BaseEditActivity;
import com.gs.SynAntiWandering.adapter.TagAdapter;
import com.gs.SynAntiWandering.apiresult.ApiResultData;
import com.gs.SynAntiWandering.constant.AllConstants;
import com.gs.SynAntiWandering.control.LabelChooseRadio;
import com.gs.SynAntiWandering.control.LabelDatePicker;
import com.gs.SynAntiWandering.control.LabelEdit;
import com.gs.SynAntiWandering.control.LabelPhoto;
import com.gs.SynAntiWandering.control.LabelText;
import com.gs.SynAntiWandering.control.LinearLayoutManager;
import com.gs.SynAntiWandering.db.dto.MemberDto;
import com.gs.SynAntiWandering.db.dto.ShortDto;
import com.gs.SynAntiWandering.db.dto.TagDto;
import com.gs.SynAntiWandering.dialog.AddTagDialog;
import com.gs.SynAntiWandering.dialog.ComboPicDialog;
import com.gs.SynAntiWandering.dialog.CommDialogUtils;
import com.gs.SynAntiWandering.dialog.LoadingDialogUtils;
import com.gs.SynAntiWandering.dialog.ShortDialog;
import com.gs.SynAntiWandering.presenter.MemberEditPresenter;
import com.gs.SynAntiWandering.util.FileUtils;
import com.gs.SynAntiWandering.util.ImageUtil;
import com.gs.SynAntiWandering.util.OKHttpUtil;
import com.gs.SynAntiWandering.util.PhotoUtil;
import com.gs.SynAntiWandering.util.SPUtil;
import com.gs.SynAntiWandering.util.ToastUtil;
import com.gs.SynAntiWandering.view.IMemberEditView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MemberEditActivity extends BaseEditActivity<IMemberEditView, MemberEditPresenter> implements IMemberEditView {

    private LabelPhoto lbPhoto;
    private LabelEdit lbCode, lbCnName, lbEnName, lbCardNo, lbIdCard, lbRoomNum, lbBedNum, lbPhone, lbEmail, lbAddress, lbRemark;
    private LabelChooseRadio lbGender;
    private LabelText lbFloor, lbState, lbType, lbShow;
    private LabelDatePicker lbEndAt, lbStartAt, lbBirthday;
    private int title;
    private List<ShortDto> listState;
    private LinearLayout layoutInfo, layoutTag;
    private List<TagDto> listTag;
    private TagAdapter adapterTag;

    @Override
    public int getLayoutId() {
        return R.layout.activity_member_edit;
    }

    @Override
    public void initView() {
        listState = new ArrayList<>();
        lbPhoto = fd(R.id.lbPhoto);
        lbCode = fd(R.id.lbCode);
        lbCnName = fd(R.id.lbCnName);
        lbEnName = fd(R.id.lbEnName);
        lbCardNo = fd(R.id.lbCardNo);
        lbIdCard = fd(R.id.lbIdCard);
        lbPhone = fd(R.id.lbPhone);
        lbGender = fd(R.id.lbGender);
        lbFloor = fd(R.id.lbFloor);
        lbType = fd(R.id.lbType);
        lbRoomNum = fd(R.id.lbRoomNum);
        lbBedNum = fd(R.id.lbBedNum);
        lbEmail = fd(R.id.lbEmail);
        lbEndAt = fd(R.id.ldEndAt);
        lbStartAt = fd(R.id.ldStartAt);
        lbBirthday = fd(R.id.ldBirthday);
        lbState = fd(R.id.lbState);
        lbAddress = fd(R.id.lbAddress);
        lbRemark = fd(R.id.lbRemark);
        layoutInfo = fd(R.id.layout_other_info);
        layoutTag = fd(R.id.layout_tag);
        listTag = new ArrayList<>();
        RecyclerView recyclerView = fd(R.id.rv_tag);
        adapterTag = new TagAdapter(this, listTag, R.layout.rvitem_tag);
        adapterTag.setOnItemChildrenClickListener((v, position) -> adapterTag.delete(position));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapterTag);
        recyclerView.setItemAnimator(null);
        recyclerView.setNestedScrollingEnabled(false);
        RadioGroup rgSort = fd(R.id.rg_sort);
        rgSort.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        MyOnClickListener onClickListener = new MyOnClickListener();
        fd(R.id.tv_add_tag).setOnClickListener(onClickListener);
        lbPhoto.setOnClickListener(onClickListener);
        lbFloor.setOnClickListener(onClickListener);
        lbType.setOnClickListener(onClickListener);
        lbState.setOnClickListener(onClickListener);
        try {
            if (!TextUtils.isEmpty(editId)) {
                mPresenter.member(editId);
            }
        } catch (Exception e) {
        }

    }

    @Override
    public void save() {
        if (TextUtils.isEmpty(getCode())) {
            ToastUtil.showToast(R.string.please_input_code);
            return;
        }
        if (TextUtils.isEmpty(getCnName())) {
            ToastUtil.showToast(R.string.p_input_cn_name);
            return;
        }
        if (TextUtils.isEmpty(getEnName())) {
            ToastUtil.showToast(R.string.p_input_en_name);
            return;
        }
        if (TextUtils.isEmpty(lbCardNo.getText())) {
            ToastUtil.showToast(R.string.p_input_card_no);
            return;
        }
//        if (TextUtils.isEmpty(getIdCard())) {
//        ToastUtil.showToast(R.string.p_input_id_card);
//            return;
//        }
        if (lbFloor.getTag() == null) {
            ToastUtil.showToast(R.string.p_sel_floor);
            return;
        }
//        if (TextUtils.isEmpty(lbRoomNum.getText())) {
//        ToastUtil.showToast(R.string.p_input_room);
//            return;
//        }
//        if (TextUtils.isEmpty(lbBedNum.getText())) {
//        ToastUtil.showToast(R.string.p_input_bed_num);
//            return;
//        }
        if (lbType.getTag() == null) {
            ToastUtil.showToast(R.string.p_sel_member_type);
            return;
        }
        if (lbState.getValId() == null) {
            ToastUtil.showToast(R.string.empty_status);
            return;
        }
        MemberDto memberDto = new MemberDto();
        if (lbPhoto.getTag() != null) {
            memberDto.setPhoto(getPhoto());
        }
        memberDto.setSiteId(SPUtil.getInstance().getString(AllConstants.SITE_ID));
        memberDto.setCode(getCode());
        memberDto.setCnName(getCnName());
        memberDto.setEnName(getEnName());
        memberDto.setCardNo(getCardNo());
        memberDto.setIdCard(getIdCard());
        memberDto.setFloorId(getFloorId());
        memberDto.setMemberTypeId(getMemberTypeId());
        memberDto.setRoomNum(getRoomNum());
        memberDto.setBedNum(getBedNum());
        memberDto.setStartAt(getStartAt());
        memberDto.setEndAt(getEndAt());
        memberDto.setBirthday(getBirthday());
        memberDto.setEmail(getEmail());
        memberDto.setSex(getSex());
        memberDto.setPhone(getPhone());
        if (lbState.getValId() != null) {
            memberDto.setState(getState());
        }
        memberDto.setAddress(getAddress());
        memberDto.setRemark(getRemark());
        memberDto.setTagNums(geTagNums());
        try {
            if (TextUtils.isEmpty(editId)) {
                mPresenter.add(memberDto);
            } else {
                memberDto.setId(editId);
                mPresenter.edit(memberDto);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public MemberEditPresenter createPresenter() {
        return new MemberEditPresenter();
    }

    @Override
    public String getId() {
        return editId;
    }

    @Override
    public String getPhoto() {
        return lbPhoto.getTag().toString();
    }

    @Override
    public String getCode() {
        return lbCode.getText();
    }

    @Override
    public String getCardNo() {
        return lbCardNo.getText();
    }

    @Override
    public String getCnName() {
        return lbCnName.getText();
    }

    @Override
    public String getEnName() {
        return lbEnName.getText();
    }

    @Override
    public String getIdCard() {
        return lbIdCard.getText();
    }

    @Override
    public Date getBirthday() {
        return lbBirthday.getDate();
    }


    @Override
    public String getEmail() {
        return lbEmail.getText();
    }

    @Override
    public Boolean getSex() {
        return lbGender.getChecked();
    }


    @Override
    public String getBedNum() {
        return lbBedNum.getText();
    }

    @Override
    public String getRoomNum() {
        return lbRoomNum.getText();
    }

    @Override
    public String getFloorId() {
        return lbFloor.getTag().toString();
    }

    @Override
    public String getMemberTypeId() {
        return lbType.getTag().toString();
    }

    @Override
    public String getPhone() {
        return lbPhone.getText();
    }

    @Override
    public Integer getState() {
        return lbState.getValId();
    }

    @Override
    public Date getStartAt() {
        return lbStartAt.getDate();
    }

    @Override
    public Date getEndAt() {
        return lbEndAt.getDate();
    }

    @Override
    public String getAddress() {
        return lbAddress.getText();
    }

    @Override
    public String getRemark() {
        return lbRemark.getText();
    }

    @Override
    public String geTagNums() {
        if (listTag.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (TagDto dto : listTag) {
            sb.append(",").append(dto.getTagNum());
        }
        return sb.substring(1);
    }

    @Override
    public void onUploadFileSuccess(ApiResultData<String> apiResult) {
        if (apiResult.getStatus() == 2000) {
            lbPhoto.setTag(apiResult.getData());
        }
    }

    @Override
    public void onUploadFileFails(Exception e) {
        ToastUtil.showToast(R.string.upload_photo_fail);
        lbPhoto.setImageResource(R.drawable.default_person);
    }

    @Override
    public void onGetComListSuccess(ApiResultData<List<ShortDto>> result) {
        if (result.getStatus() != 2000) {
            ToastUtil.showToast(result.getMessage());
            return;
        }
        new ShortDialog(MemberEditActivity.this, result.getData(), title, lbShow.getTag() != null ? lbShow.getTag().toString() : "",
                bean -> {
                    lbShow.setTag(bean.getId());
                    lbShow.setText(bean.getName());
                }).show();
    }

    @Override
    public void onGetComListFails(Exception msg) {
        ToastUtil.showToast( R.string.network_error);
    }

    @Override
    public void onGetTagListSuccess(ApiResultData<List<TagDto>> result) {
        if (result.getStatus() != 2000) {
            ToastUtil.showToast(result.getMessage());
            return;
        }
        List<TagDto> data = result.getData();
        if (data == null) {
            ToastUtil.showToast(R.string.null_data);
            return;
        }
        if (!data.isEmpty()) {
            for (TagDto bean : listTag) {
                for (int i = 0; i < data.size (); i++) {
                    if (bean.getTagNum().equals(data.get(i).getTagNum())) {
                        if (data.get(i).getState() != 1) {
                            data.get(i).setState(1);
                        }
                        break;
                    }
                }
            }
        }
        new AddTagDialog(MemberEditActivity.this, data, () -> {
            listTag.clear();
            for (TagDto dto : data) {
                if (dto.getState() != null && dto.getState() == 1) {
                    listTag.add(dto);
                }
            }
            adapterTag.notifyDataSetChanged();
        }).show();
    }

    @Override
    public void onGetTagListFails(Exception msg) {
        ToastUtil.showToast( R.string.network_error);
    }

    @Override
    public void onGetMemberSuccess(ApiResultData<MemberDto> apiResult) {
        if (apiResult.getStatus() != 2000 || apiResult.getData() == null) {
            ToastUtil.showToast(apiResult.getMessage());
            return;
        }
        MemberDto data = apiResult.getData();
        if (!TextUtils.isEmpty(data.getPhoto())) {
            lbPhoto.setTag(data.getPhoto());
            lbPhoto.loadPic(OKHttpUtil.IMG_URL + data.getPhoto());
        }
        lbCode.setText(data.getCode());
        lbCnName.setText(data.getCnName());
        lbEnName.setText(data.getEnName());
        lbCardNo.setText(data.getCardNo());
        lbIdCard.setText(data.getIdCard());
        lbRoomNum.setText(data.getRoomNum() == null?"":data.getRoomNum());
        lbBedNum.setText(data.getBedNum() == null?"":data.getBedNum());
        if (data.getFloor() != null) {
            lbFloor.setText(data.getFloor().getName());
            lbFloor.setTag(data.getFloor().getId());
        }
        if (data.getMemberType() != null) {
            lbType.setText(data.getMemberType().getName());
            lbType.setTag(data.getMemberType().getId());
        }
        if (data.getEndAt() != null) {
            lbEndAt.setDate(data.getEndAt());
        }
        if (data.getStartAt() != null) {
            lbStartAt.setDate(data.getStartAt());
        }
        if (data.getBirthday() != null) {
            lbBirthday.setDate(data.getBirthday());
        }
        lbEmail.setText(data.getEmail());
        lbGender.setChecked(data.getSex());
        lbPhone.setText(data.getPhone());
        lbState.setValId(data.getState());
        lbState.setText(data.getStateName());
        lbAddress.setText(data.getAddress());
        lbRemark.setText(data.getRemark());
        if (data.getTags() != null) {
            listTag.addAll(data.getTags());
            adapterTag.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetMemberFails(Exception e) {
        ToastUtil.showToast( R.string.network_error);
    }

    @Override
    public void onAddMemberSuccess(ApiResultData<String> apiResult) {
        ToastUtil.showToast(apiResult.getMessage());
        back(apiResult.getStatus());
    }

    @Override
    public void onAddMemberFails(Exception e) {
        ToastUtil.showToast( R.string.network_error);
    }

    @Override
    public void onEditMemberSuccess(ApiResultData<String> apiResult) {
        ToastUtil.showToast(apiResult.getMessage());
        back(apiResult.getStatus());
    }

    @Override
    public void onEditMemberFails(Exception e) {
        ToastUtil.showToast( R.string.network_error);
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class MyOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.lbPhoto) {
                CommDialogUtils.showCommboPicDialog(MemberEditActivity.this, "");
            } else if (id == R.id.lbFloor) {
                try {
                    title = R.string.p_sel_floor;
                    lbShow = lbFloor;
                    mPresenter.getComboList("floors");
                } catch (Exception e) {

                }
            } else if (id == R.id.lbType) {
                try {
                    title = R.string.p_sel_member_type;
                    lbShow = lbType;
                    mPresenter.getComboList("memberTypes");
                } catch (Exception e) {

                }
            } else if (id == R.id.lbState) {
                if (listState.size() == 0) {
                    ShortDto bean3 = new ShortDto("0", getString(R.string.state_0));
                    ShortDto bean1 = new ShortDto("1", getString(R.string.state_1));
                    ShortDto bean2 = new ShortDto("2", getString(R.string.state_2));
                    listState.add(bean3);
                    listState.add(bean1);
                    listState.add(bean2);
                }
                new ShortDialog(MemberEditActivity.this, listState, R.string.p_sel_state, lbState.getValId() + "",
                        bean -> {
                            lbState.setValId(Integer.valueOf(bean.getId()));
                            lbState.setText(bean.getName());
                        }).show();
            } else if (id == R.id.tv_add_tag) {
                try {
                    mPresenter.getTagList(editId);
                } catch (Exception e) {

                }
            }
        }
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.rb_info) {
                layoutInfo.setVisibility(View.VISIBLE);
                layoutTag.setVisibility(View.GONE);
            } else {
                layoutTag.setVisibility(View.VISIBLE);
                layoutInfo.setVisibility(View.GONE);
            }
        }
    }

    private void decodeImage(String path) {
        try {
            mPresenter.uploadFile(path);
            lbPhoto.loadPic(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0) {
            if (requestCode == AllConstants.PIC_CAMERA) {
                String url = ImageUtil.getInstance().handlePhoto(this);
                decodeImage(url);
            } else if (requestCode == AllConstants.PIC_GALLERY) {
                decodeImage(FileUtils.getFilePathByUri(this, data.getData()));
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 申请相机权限后返回
            if (requestCode == ComboPicDialog.PIC_CAREMA) {
                PhotoUtil.getInstance().toCamera(this);
            }
            // 申请读取图库权限后返回
            else if (requestCode == ComboPicDialog.PIC_GALLERY) {
                PhotoUtil.getInstance().toGallery(this);
            }
        }
    }
}